﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.IO;
using School.Entities;
using School.Common;
using System.Data.Entity;
using School.Admission;
using System.Data;


namespace School.Pages.Admission
{
    public partial class StudentClasses : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if ((IQueryable<int>)Session["privilage"] != null)
            {
                var x = (IQueryable<int>)Session["privilage"];

                if (x.Contains(1013) == true)
                {
                    if (!(Page.IsPostBack))
                    {

                        Fillcrls();
                        InitializeControls();
                        GridDataBind();

                    }
                }
                else
                    Response.Redirect("../organization/no_privelege.aspx");
            }
            else
                Response.Redirect("../organization/no_privelege.aspx");
        }
        # region "Collect Data"

        //***************** This is function to bind data grid  ***************************
        //-**************************************************************************
        protected void GridDataBind()
        {
            Int32 mycount;
            Hashtable SearchTable = new Hashtable();

            if (ddlSearchClass_Id.SelectedIndex > 0)
            {
                SearchTable.Add("Class_Id", ddlSearchClass_Id.SelectedValue.ToString());
            }
            griddata.DataSource = Class_Student.All(SearchTable);
            
            griddata.DataBind();
            

            griddata.Visible = true;
            mycount = griddata.Rows.Count;
            lblRecordNo.Text = "عدد نتائج البحث = " + mycount.ToString();
            if (mycount == 0)
            {
                lblMessage.Text = "لا يوجد بيانات";
            }
            else
            {
                lblMessage.Text = "";
            }

        }

        # endregion


        # region "Fill all crls"

        //***************** This is function to fill crl  ***************************
        //-**************************************************************************

        protected void Fillcrls()
        {

            ddlcampus_Id.DataSource = Structure.GetCampuses();
            ddlcampus_Id.DataTextField = "Name";
            ddlcampus_Id.DataValueField = "Id";
            ddlcampus_Id.DataBind();
            ddlcampus_Id.Items.Insert(0, new ListItem("اختيار", "-1"));

            ddlSearchcampus_Id.DataSource = Structure.GetCampuses();
            ddlSearchcampus_Id.DataTextField = "Name";
            ddlSearchcampus_Id.DataValueField = "Id";
            ddlSearchcampus_Id.DataBind();
            ddlSearchcampus_Id.Items.Insert(0, new ListItem("اختيار", "-1"));

            ddlCertificate_Id.DataSource = Structure.GetCertificates();
            ddlCertificate_Id.DataTextField = "Name";
            ddlCertificate_Id.DataValueField = "Id";
            ddlCertificate_Id.DataBind();
            ddlCertificate_Id.Items.Insert(0, new ListItem("اختيار", "-1"));

            
            ddlGrade_Id.DataSource = Structure.GetGrades();
            ddlGrade_Id.DataTextField = "Name";
            ddlGrade_Id.DataValueField = "id";
            ddlGrade_Id.DataBind();
            ddlGrade_Id.Items.Insert(0, new ListItem("اختيار", "-1"));

            ddlStage_Id.DataSource = Structure.GetStages();
            ddlStage_Id.DataTextField = "Name";
            ddlStage_Id.DataValueField = "id";
            ddlStage_Id.DataBind();
            ddlStage_Id.Items.Insert(0, new ListItem("اختيار", "-1"));

            ddlEductionalYear_Id.DataSource = Structure.GetCurrentEductionalYear();
            ddlEductionalYear_Id.DataTextField = "Name";
            ddlEductionalYear_Id.DataValueField = "id";
            ddlEductionalYear_Id.DataBind();

            ddlSearchEductionalYear_Id.DataSource = Structure.GetCurrentEductionalYear();
            ddlSearchEductionalYear_Id.DataTextField = "Name";
            ddlSearchEductionalYear_Id.DataValueField = "id";
            ddlSearchEductionalYear_Id.DataBind();
            
        }


        //***************** This is function to initlaize crl  ***************************
        //-**************************************************************************
        protected void InitializeControls()
        {

        }

        # endregion


        # region "Mode Handlers"

        //***************** This is function to handle page in add mode  ***************************
        //-**************************************************************************
        protected void PutFormInAddMode()
        {

        }


        //***************** This is function to handle page in brows mode  ***************************
        //-**************************************************************************

        protected void PutFormInBrwosMode()
        {
            pnlAdd.Visible = false;
            pnlbrows.Visible = false;

        }

        #endregion


        # region "Grid Events ***********"

        //***************** This is function to handle page when Page Index Changing   ***************************
        //-**************************************************************************

        protected void griddata_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            griddata.PageIndex = e.NewPageIndex;
            GridDataBind();
        }


        //***************** This is function to handle page when Row Deleting  ***************************
        //-**************************************************************************

        protected void griddata_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            try
            {
                griddata.SelectedIndex = e.RowIndex;

                long CID = Int32.Parse(griddata.SelectedDataKey.Value.ToString());
                Boolean successadd = Test_Appointment.Delete(CID);
                if (successadd == true)
                {
                    GridDataBind();
                    lblMessage.Visible = true;
                    lblMessage.Text = "تم حذف البيانات بنجاح";

                }
            }
            catch (Exception)
            {
                lblMessage.Text = "  لم يتم حذف البيانات بنجاح رجاء مراجعة مدير النظام";

            }

        }


        //***************** This is function to handle page when Row Data Bound  ***************************
        //-**************************************************************************
        protected void griddata_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                LinkButton LB = (LinkButton)e.Row.FindControl("LinkButton1");
                LB.Attributes.Add("onclick", "javascript:return " +
                "confirm('Are you sure you want to delete record(s) (" +
                DataBinder.Eval(e.Row.DataItem, "Id") + ") ?')");
            }
        }

        protected void griddata_SelectedIndexChanged(object sender, EventArgs e)
        {
            
            pnlAdd.Visible = false;
            pnlbrows.Visible = false;
            PnlResults.Visible = true;
            
            DetailsView1bind();
           
        }

        protected void DetailsView1bind()
        {
            
            //Hashtable SearchTable = new Hashtable();

            
            //ADM_Test_Appointment app=  Test_Appointment.Single(long.Parse(griddata.SelectedDataKey.Value.ToString())); 
            //SearchTable.Add("Student_Id",app.Student_Id );
            //SearchTable.Add("Test_Id", app.Test_Id);
            //IEnumerable<ADM_Student_Subject> studentsubjects = Student_Subject.All(SearchTable);
            //ResultsGridView.DataSource = studentsubjects ;

            //ResultsGridView.DataBind();
           
            //lblStudentName.Text = studentsubjects.ElementAt(0).TE_Student.Ar_FirstName + " " + studentsubjects.ElementAt(0).TE_Student.Ar_SecondName + " " + studentsubjects.ElementAt(0).TE_Student.Ar_ThirdNmae + " " + studentsubjects.ElementAt(0).TE_Student.Ar_FourthName;
            //Session["StudentId"] = studentsubjects.ElementAt(0).Student_Id.ToString();
            //Session["EductionalYear"] = studentsubjects.ElementAt(0).ADM_Test.EductionalYear_Id.ToString();  
        }



        # endregion



        # region   "Execute commands sent to the form"



        //***************** This is function to handle page when Puser click in الغاء btn  ***************************
        //-**************************************************************************
        protected void btnCancel_Click(object sender, EventArgs e)
        {

        }


        //***************** This is function to handle page when Puser click in اضافة btn  ***************************
        //-**************************************************************************

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            pnlAdd.Visible = true;
            pnlbrows.Visible = false;
            pnldetails.Visible = false;
        }

        //***************** This is function to handle page when Puser click in انهاء btn  ***************************
        //-**************************************************************************


        protected void btnend_Click(object sender, EventArgs e)
        {
            btnAdd.Visible = true;
            pnlAdd.Visible = false;
            pnlbrows.Visible = true;
            PnlResults.Visible = false;
            GridDataBind();
        }
        //***************** This is function to handle page when Puser click in حفظ btn  ***************************
        //-**************************************************************************

        protected void btnSave_Click(object sender, EventArgs e)
        {

            Int32 Teacher;

            long xx = 0 ;
            String SortType="";
            Int32 Classcounter, CapacityCounter, Capacity, StudentCounter, AllclassCapacity=0;
            Int32 ExamTime = 0;

            switch (rblSearchType.SelectedValue)
            {
                case "0":
                    SortType = "Alpha";
                        break;
                case "1":
                    SortType = "Birthday";
                        break;
                case "2":
                    SortType = "Gender";
                        break;
            }
            
            IEnumerable<TE_Student> Studentslist = Student.GetStudentsForClasses(5,long.Parse(ddlGrade_Id.SelectedValue),SortType);
            IEnumerable<ORG_Class> ClassList=  Structure.GetClassesByGrade(long.Parse(ddlGrade_Id.SelectedValue));
            StudentCounter = 0;
            Classcounter = 0;
            
            while (Classcounter < ClassList.Count())
            {
                AllclassCapacity += int.Parse(ClassList.ElementAt(Classcounter).Capacity.ToString());
                Classcounter += 1;
            }

            if (Studentslist.Count() > AllclassCapacity)
            {
                lblMessageAdd.Text = "لا يمكن توزيع الطلاب علي الفصول . عدد الطلاب اكبر من سعة الفصول";
                return;
            }

            if (Studentslist.Count() ==  0 )
            {
                lblMessageAdd.Text = "لا يوجد طلاب ملحقين علي هذا الصف";
                return;
            }
            Classcounter = 0;
            try
            {
                while (Classcounter < ddlClass_Id.Items.Count)
                {
                    CapacityCounter = 0;
                    Capacity = int.Parse(ClassList.ElementAt(Classcounter).Capacity.ToString());
                    while ( CapacityCounter < Capacity)
                    {
                        Class_Student.Add(new TE_Class_Student{
                        Class_Id=ClassList.ElementAt(Classcounter).Id,
                        Student_Id = Studentslist.ElementAt(StudentCounter).Id,
                        EductionalYear_Id= long.Parse(ddlEductionalYear_Id.SelectedValue)
                        });
                    CapacityCounter += 1;
                    StudentCounter += 1;
                        if (StudentCounter==Studentslist.Count())
                        {
                            lblMessageAdd.Text = "تم حفظ البيانات بنجاح";
                            return;
                        }
                    }
                    Classcounter += 1;
                }

                
                InitializeControls();
            }
            catch
            {
                lblMessageAdd.Text = "لم يتم حفظ البيانات";
            }

        }


        # endregion



        # region " Search *********************"




        //***************** This is function to search by  Get All btn ***************************
        //-**************************************************************************
        protected void btnGetAll_Click(object sender, EventArgs e)
        {


            GridDataBind();
        }



        protected void btnSearch_Click(object sender, EventArgs e)
        {
            GridDataBind();
        }

        # endregion

        protected void ddlCertificate_Id_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlCertificate_Id.SelectedIndex > 0)
            {
                ddlStage_Id.Items.Clear();
                ddlGrade_Id.Items.Clear();
                ddlStage_Id.DataSource = Structure.GetStagesByCertificate(Convert.ToInt64(ddlCertificate_Id.SelectedValue));
                ddlStage_Id.DataTextField = "Name";
                ddlStage_Id.DataValueField = "id";
                ddlStage_Id.DataBind();
                ddlStage_Id.Items.Insert(0, new ListItem("اختيار", "-1"));
                ddlStage_Id.Enabled = true;
                ddlGrade_Id.Enabled = false;
            }
        }

        protected void ddlStage_Id_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlStage_Id.SelectedIndex > 0)
            {

                ddlGrade_Id.Items.Clear();
                ddlGrade_Id.DataSource = Structure.GetGradesByStage(Convert.ToInt64(ddlStage_Id.SelectedValue));
                ddlGrade_Id.DataTextField = "Name";
                ddlGrade_Id.DataValueField = "id";
                ddlGrade_Id.DataBind();
                ddlGrade_Id.Items.Insert(0, new ListItem("اختيار", "-1"));
                ddlGrade_Id.Enabled = true;
            }
        }

        protected void ddlGrade_Id_SelectedIndexChanged(object sender, EventArgs e)
        {
            IEnumerable<TE_Student> Studentslist = Student.GetStudentsForClasses(5, long.Parse(ddlGrade_Id.SelectedValue), "Alpha");
            lblStudentCount.Visible = true;
            lblStudentCount.Text = Studentslist.Count().ToString();

            ddlClass_Id.DataSource = Structure.GetClassesByGrade(long.Parse(ddlGrade_Id.SelectedValue));
            ddlClass_Id.DataTextField = "Name";
            ddlClass_Id.DataValueField = "Id";
            ddlClass_Id.DataBind();
        }

        protected void ddlcampus_Id_SelectedIndexChanged(object sender, EventArgs e)
        {
            {
                ddlCertificate_Id.Items.Clear();
                ddlGrade_Id.Items.Clear();
                ddlStage_Id.Items.Clear();
                ddlCertificate_Id.DataSource = Structure.GetCertificatesByCampus(Convert.ToInt64(ddlcampus_Id.SelectedValue));
                ddlCertificate_Id.DataTextField = "Name";
                ddlCertificate_Id.DataValueField = "Id";
                ddlCertificate_Id.DataBind();
                ddlCertificate_Id.Items.Insert(0, new ListItem("اختيار", "-1"));
                ddlCertificate_Id.Enabled = true;
                ddlGrade_Id.Enabled = false;
                ddlStage_Id.Enabled = false;
            }
        }

        protected void txtShowCampus_TextChanged(object sender, EventArgs e)
        {

        }

        protected void ddlSearchcampus_Id_SelectedIndexChanged(object sender, EventArgs e)
        {
            {
                ddlSearchCertificate_Id.Items.Clear();
                ddlSearchGrade_ID.Items.Clear();
                ddlSearchStage_Id.Items.Clear();
                ddlSearchCertificate_Id.DataSource = Structure.GetCertificatesByCampus(Convert.ToInt64(ddlSearchcampus_Id.SelectedValue));
                ddlSearchCertificate_Id.DataTextField = "Name";
                ddlSearchCertificate_Id.DataValueField = "Id";
                ddlSearchCertificate_Id.DataBind();
                ddlSearchCertificate_Id.Items.Insert(0, new ListItem("اختيار", "-1"));
                ddlSearchCertificate_Id.Enabled = true;
                ddlSearchGrade_ID.Enabled = false;
                ddlSearchStage_Id.Enabled = false;
            }
        }

        protected void btnback_Click(object sender, EventArgs e)
        {

        }

        

        

        protected void ddlTeacher_Id_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        protected void ResultsGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {

        }

        protected void ResultsGridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {

        }

        protected void ResultsGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {

        }

        protected void ResultsGridView_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        protected void ResultsGridView_RowEditing(object sender, GridViewEditEventArgs e)
        {
            //ResultsGridView.EditIndex = e.NewEditIndex;
            //DetailsView1bind ();
        }

        protected void ResultsGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            //ADM_Student_Subject s = Student_Subject.Single(long.Parse(e.Keys[0].ToString()));
            //Student_Subject.Update(new ADM_Student_Subject
            //{
            //    Id = s.Id,
            //    Test_Id = s.Test_Id ,
            //    Student_Id=s.Student_Id ,
            //    Subject_Id= s.Subject_Id,
            //    Degree = Double.Parse(e.NewValues[0].ToString())
            //});
            //ResultsGridView.EditIndex = -1;
            //DetailsView1bind();
        }

        protected void ResultsGridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            //ResultsGridView.EditIndex = -1;
            //DetailsView1bind();
        }

        protected void btnChangeStatus_Click(object sender, EventArgs e)
        {
            //Student.UpdateStatusId(new TE_Student
            //{
            //    Id = long.Parse(Session["StudentId"].ToString()),
            //    Status_Id = int.Parse(rblStatusType.SelectedValue )
            //}
            //);
            //TE_Student mystudent = Student.Single(long.Parse(Session["StudentId"].ToString()));

            //if (StudentTransaction.Add(new ADM_Student_Transaction
            //{
            //    Student_Id = mystudent.Id,
            //    Status_Id = int.Parse(rblStatusType.SelectedValue),
            //    EductionalYear_Id = long.Parse(Session["EductionalYear"].ToString()),
            //    Campus_Id = mystudent.Campus_Id,
            //    Certificate_Id = mystudent.Certificate_Id,
            //    Stage_Id = mystudent.Stage_Id,
            //    Grad_Id = mystudent.Grade_ID
            //}) != 0)
            //{
            //    lblMessageDetails.Text = "تم تغيير حالة الطالب بنجاح";
            //}
            //else
            //{
            //    lblMessageDetails.Text = "لم يتم تغيير حالة الطالب";
            //}
            //;
        }

        
        protected void ddlSearchCertificate_Id_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlSearchCertificate_Id.SelectedIndex > 0)
            {
                ddlSearchStage_Id.Items.Clear();
                ddlSearchGrade_ID.Items.Clear();
                ddlSearchStage_Id.DataSource = Structure.GetStagesByCertificate(Convert.ToInt64(ddlSearchCertificate_Id.SelectedValue));
                ddlSearchStage_Id.DataTextField = "Name";
                ddlSearchStage_Id.DataValueField = "id";
                ddlSearchStage_Id.DataBind();
                ddlSearchStage_Id.Items.Insert(0, new ListItem("اختيار", "-1"));
                ddlSearchStage_Id.Enabled = true;
                ddlSearchGrade_ID.Enabled = false;
            }
        }

        protected void ddlSearchStage_Id_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlSearchStage_Id.SelectedIndex > 0)
            {

                ddlSearchGrade_ID.Items.Clear();
                ddlSearchGrade_ID.DataSource = Structure.GetGradesByStage(Convert.ToInt64(ddlSearchStage_Id.SelectedValue));
                ddlSearchGrade_ID.DataTextField = "Name";
                ddlSearchGrade_ID.DataValueField = "id";
                ddlSearchGrade_ID.DataBind();
                ddlSearchGrade_ID.Items.Insert(0, new ListItem("اختيار", "-1"));
                ddlSearchGrade_ID.Enabled = true;
            }
        }

        protected void ddlSearchGrade_ID_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlSearchGrade_ID.SelectedIndex > 0)
            {
                ddlSearchClass_Id.DataSource = Structure.GetClassesByGrade(long.Parse(ddlSearchGrade_ID.SelectedValue));
                ddlSearchClass_Id.DataTextField = "Name";
                ddlSearchClass_Id.DataValueField = "Id";
                ddlSearchClass_Id.DataBind();
                ddlSearchClass_Id.Items.Insert(0, new ListItem("اختيار", "-1"));
            }
        }

        protected void ddlEductionalYear_Id_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        protected void btnReport_Click(object sender, EventArgs e)
        {
            if (ddlSearchClass_Id.SelectedIndex > 0)
            {
                Session["Class_Id"] = ddlSearchClass_Id.SelectedValue;
                Session["EductionalYear_Id"] = Structure.GetCurrentEductionalYear().First().Id;
                string strbScript = "";
                strbScript = "<script language='javascript'>";
                strbScript = strbScript + "window.open('Reports/ShowClassReport.aspx', true, 'height=600,width=800,status=no,toolbar=no,menubar=no,location=no')";
                strbScript = strbScript + "</script>";

                Response.Write(strbScript);
            }
            else
            {
                lblMessage.Text = "برجاء اختيار احد الفصول من القائمة";
            }

        }
    }
}